import os

import requests
import json


class RUFUSCloudAPI:
    def __init__(self, api_key, machineid, eventid, firmware_version="0.0.0", hardwaretype="", position1="未知位置",
                 position2="未知位置", session_alias="未知赛事", timezone=""):

        self.api_key = api_key
        self.base_url = "https://api.runonrufus.com/v0"
        self.eventid = eventid
        self.firmware_version = firmware_version
        self.hardwaretype = hardwaretype
        self.machineid = machineid
        self.position1 = position1
        self.position2 = position2
        self.session_alias = session_alias
        self.timezone = timezone
        self.num_passing = 0
        # self.rufus_info_file_path = "/home/feibot/rurufus_info.json"
        self.rufus_info_file_path = "rufus_info.json"
        self.deviceid = self.get_or_create_device()
        self.session = self.get_or_create_session()

    def validate_api_key(self):
        """验证API密钥是否有效"""
        url = f"{self.base_url}/validate"
        headers = {
            "Content-Type": "application/json",
            "api_key": self.api_key,
        }
        response = requests.get(url, headers=headers)
        return response.json()

    def get_all_devices(self):
        """获取所有设备的deviceid列表"""
        url = f"{self.base_url}/devices"
        headers = {
            "Content-Type": "application/json",
            "api_key": self.api_key,
        }
        response = requests.get(url, headers=headers)
        # 解析响应数据，提取deviceid列表
        data = response.json()
        device_ids = [item['deviceid'] for item in data['body']['result']]
        return device_ids

    def create_device(self) -> str:
        """创建新设备返回设备ID"""
        url = f"{self.base_url}/devices"
        headers = {
            "Content-Type": "application/json",
            "api_key": self.api_key,
        }
        body = {
            "model": self.hardwaretype,
            "serial_number": self.position1,
            "alias": self.machineid,
            "firmware": self.firmware_version,
        }
        response = requests.post(url, headers=headers, json=body)
        if response.status_code == 201:
            try:
                device_id = response.json()['body']['deviceid']
            except KeyError:
                print("deviceid not found in the response")
                device_id = ""
        else:
            device_id = ""
        return device_id

    def get_or_create_device(self) -> str:
        """从JSON读取device_id，若无则创建并保存"""
        data = {}

        if os.path.exists(self.rufus_info_file_path):
            with open(self.rufus_info_file_path, "r") as f:
                try:
                    data = json.load(f)
                except json.JSONDecodeError:
                    data = {}

        device_id = data.get("device_id")

        if not device_id:
            device_id = self.create_device()
            if device_id:
                data["device_id"] = device_id
                with open(self.rufus_info_file_path, "w") as f:
                    json.dump(data, f, indent=2)

        return device_id

    def get_device_info(self, device_id):
        """按设备ID获取特定设备详细信息"""
        url = f"{self.base_url}/devices/{device_id}"
        headers = {
            "Content-Type": "application/json",
            "api_key": self.api_key,
        }
        response = requests.get(url, headers=headers)
        return response.json()

    def delete_device(self, device_id) -> bool:
        """删除设备"""
        url = f"{self.base_url}/devices/{device_id}"
        headers = {
            "Content-Type": "application/json",
            "api_key": self.api_key,
        }
        response = requests.delete(url, headers=headers)
        print("Delete device " + device_id)
        return response.status_code == 204  # 是否删除成功

    def delete_all_devices(self):
        """删除所有设备"""
        device_ids = self.get_all_devices()
        for device_id in device_ids:
            self.delete_device(device_id)
        os.system(f"rm -f {self.rufus_info_file_path}")

    def get_or_create_session(self):
        """从 JSON 中获取或创建 eventid 对应的 token_session，并初始化 num_passing"""
        data = {}
        if os.path.exists(self.rufus_info_file_path):
            with open(self.rufus_info_file_path, "r") as f:
                try:
                    data = json.load(f)
                except json.JSONDecodeError:
                    data = {}

        sessions = data.get("sessions", {})

        if self.eventid in sessions:
            session_data = sessions[self.eventid]
            self.num_passing = session_data.get("num_passing", 0)
            return session_data["token_session"]

        # 不存在则创建新会话
        url = f"{self.base_url}/sessions"
        headers = {
            "Content-Type": "application/json",
            "api_key": self.api_key,
        }
        body = {
            "deviceid": self.deviceid,
            "alias": self.session_alias,
        }

        response = requests.post(url, headers=headers, json=body)
        token_session = response.json()["body"]["token_session"]

        # 保存新会话 + num_passing
        sessions[self.eventid] = {
            "token_session": token_session,
            "num_passing": 0
        }
        data["sessions"] = sessions
        with open(self.rufus_info_file_path, "w") as f:
            json.dump(data, f, indent=2)

        self.num_passing = 0
        return token_session

    def get_session_by_device(self, device_id):
        """获取设备的会话"""
        url = f"{self.base_url}/sessions/device/{device_id}"
        headers = {
            "Content-Type": "application/json",
            "api_key": self.api_key,
        }
        response = requests.get(url, headers=headers)
        return response.json()

    def get_active_session(self, device_id):
        """获取设备激活的会话"""
        url = f"{self.base_url}/sessions/device/{device_id}/active"
        headers = {
            "Content-Type": "application/json",
            "api_key": self.api_key,
        }
        response = requests.get(url, headers=headers)

        return response.json()

    def close_session(self, session_id):
        """关闭会话"""
        url = f"{self.base_url}/sessions/close/{session_id}"
        headers = {
            "Content-Type": "application/json",
            "api_key": self.api_key,
        }
        response = requests.patch(url, headers=headers)
        return response.status_code == 200

    def get_session_info(self, session_id):
        """获取单个会话的详细信息
        
        Args:
            session_id (str): 会话token标识符
            
        Returns:
            dict: 会话详细信息
        """
        url = f"{self.base_url}/sessions/{session_id}"
        headers = {
            "Content-Type": "application/json",
            "api_key": self.api_key,
        }
        response = requests.get(url, headers=headers)
        return response.json()

    def get_passings(self, session_id):
        """获取会话中的所有通行记录"""
        url = f"{self.base_url}/sessions/{session_id}/passings"
        headers = {
            "Content-Type": "application/json",
            "api_key": self.api_key,
        }
        response = requests.get(url, headers=headers)
        return response.json()

    def create_passing_list(self, passing_data):
        """生成通行记录列表
        
        Args:
            passing_data (list): 通行记录数据列表，每个元素为[bib, timestamp]格式的列表
                bib: 参赛号码
                timestamp: 时间戳，格式: YYYY-MM-DDTHH:mm:ss.sssZ
            
        Returns:
            list: 通行记录列表
        """
        passinglist = []
        data = {}
        for epc, timestamp in passing_data:
            self.num_passing += 1
            passing = {
                "bib": "",  # 留空，从后台匹配芯片码
                "num_passing": self.num_passing,
                "timestamp": timestamp,
                # "latitude": self.position1,
                # "longitude": self.position2,
                "timezone": self.timezone,
                "status": "Sent",
                # "participant_id":"" ,根据bib生成participant_id
                "chip": str(epc)
            }
            passinglist.append(passing)
        # 更新num_passing到本地记录
        if os.path.exists(self.rufus_info_file_path):
            with open(self.rufus_info_file_path, "r") as f:
                try:
                    data = json.load(f)
                except json.JSONDecodeError:
                    pass
        if "sessions" not in data:
            data["sessions"] = {}
        if self.eventid not in data["sessions"]:
            data["sessions"][self.eventid] = {}
        data["sessions"][self.eventid]["num_passing"] = self.num_passing
        with open(self.rufus_info_file_path, "w") as f:
            json.dump(data, f, indent=2)
        return passinglist

    def add_passing_record(self, passing_data):
        """创建新的通行记录
        
        Args:
            passing_data (list): 通行记录数据列表，每个元素为[epc, timestamp]格式的列表
        Returns:
            dict: API响应数据
        """
        passings_list = self.create_passing_list(passing_data)

        url = f"{self.base_url}/passings"
        headers = {
            "Content-Type": "application/json",
            "api_key": self.api_key,
        }
        data = {
            "token_session": self.session,
            "passings_list": passings_list
        }
        response = requests.post(url, headers=headers, json=data)
        return response.json()

    def get_passing(self, session_id, passing_id):
        """获取特定通行记录详细信息"""
        url = f"{self.base_url}/sessions/{session_id}/passings/{passing_id}"
        headers = {
            "Content-Type": "application/json",
            "api_key": self.api_key,
        }
        response = requests.get(url, headers=headers)
        return response.json()

    def delete_passing(self, session_id, passing_id):
        """删除通行记录"""
        url = f"{self.base_url}/sessions/{session_id}/passings/{passing_id}"
        headers = {
            "Content-Type": "application/json",
            "api_key": self.api_key,
        }
        response = requests.delete(url, headers=headers)
        return response.status_code == 204

    def get_session_statistics(self, session_id):
        """获取会话统计信息"""
        url = f"{self.base_url}/sessions/{session_id}/statistics"
        headers = {
            "Content-Type": "application/json",
            "api_key": self.api_key,
        }
        response = requests.get(url, headers=headers)
        return response.json()


if __name__ == "__main__":
    pass
    # api_key = "ror-1473ba930a7271b6b8c3"
    # rufus_api = RUFUSCloudAPI(api_key, "U000", "0001", "1.0.0", "F800", "START_10K", "16074", "测试赛事",
    #                           "Asia/Shanghai")
    # 测试内容
    # passing_data = [
    #     ["A0001", "2025-01-22T09:20:25.000Z"],
    #     ["A0002", "2025-01-22T09:21:33.000Z"],
    #     ["A0003", "2025-01-22T09:22:41.000Z"],
    #     ["A0004", "2025-01-22T09:23:49.000Z"],
    #     ["A0005", "2025-01-22T09:24:57.000Z"],
    #     ["A0006", "2025-01-22T09:26:05.000Z"],
    #     ["A0007", "2025-01-22T09:27:13.000Z"],
    #     ["A0008", "2025-01-22T09:28:21.000Z"],
    #     ["A0009", "2025-01-22T09:29:29.000Z"],
    # ]
    # result = rufus_api.add_passing_record(passing_data)
    # print(result)
    # print(id)
    # print(rufus_api.get_device_info(id),file=open("device_info.json","a",encoding="utf-8"))
    # print(session)
    # print(rufus_api.close_session(session))
    # print (rufus_api.get_session_info(session))

    # rufus_api.delete_all_devices()
